//
//  QDMainPageTableViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/7.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON


/// 主页控制器
final class QDMainPageTableViewController: NWTableViewController {

    /// 主页cell的样式
    enum QDMainPageCellType: String,CaseIterable {
        /// 顶部的轮播
        case topImageList = "topImageList"
        /// 子模块样式
        case functionList = "functionList"
        /// 公告/紧急公告
        case notices = "notices"
        /// 广告
        case advertise = "advertise"
        /// 附近站点
        case station = "station"
        /// 资讯
        case documents = "documents"
    }
    
    /// 模拟标题
    lazy private var titleView: UIView = {
        
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    /// 显示畅达幸福
    lazy private var titleLabel: UILabel = {
        
        let label = UILabel()
        label.backgroundColor = .white
        label.text = "畅达幸福"
        label.font = Font.medium.font(size: 18)
        label.textColor = QDColors.black
        
        return label

    }()
    
    /// 消息的按钮
    lazy private var messageButton: UIButton = {
        
        let messageButton = UIButton()
        
        messageButton.adjustsImageWhenHighlighted = false
        messageButton.backgroundColor = .white
        messageButton.setImage("mp_notice".namedImage, for: .normal)
        messageButton.addTarget(self, action: #selector(pushToMessageListViewController), for: .touchUpInside)
        
        return messageButton
    }()
    
    
    /// 资讯上方的headerView
    lazy private var sectionHeaderView: QDMPSectionHeaderView = {
        
        let headerView = QDMPSectionHeaderView()
        
        headerView.moreButton.addTarget(self, action: #selector(pushToNewsListViewController), for: .touchUpInside)
        
        return headerView
    }()
    
    /// 定位管理者
    private let locationManager = QDLocationManager()
    
    // MARK: 数据
    /// 附近站点
    private var nearByStation = QDNearMetroStationContainer()
    /// 资讯列表
    private var documents = [QDDocumentsModel]()
    /// 子模块
    private var functionList = [QDFunctionModel]()
    /// 顶部的轮播
    private var imgList = [QDImageListModel]()
    /// 广告位
    private var advertisement = [QDAdvertisementModel]()
    /// 公告
    private var notices = [QDNoticesModel]()
    /// section的数量
    private var numberOfSections = 6
    /// 站点是否是折叠
    @available(iOS,deprecated: 9.0, message: "不再使用")
    private var stationIsfold = true
    /// 记录itemCell 是否变化flowLayout
    private var itemCount = -1
    
    /// 是否存在禁止公告
    private var hasNotice: Bool {
        return notices.count > 0
    }
    
    /// tableView的固定样式表
    private var cellTypes: [QDMainPageCellType]{
        get {
            if hasNotice { // 存在紧急公告
                return QDMainPageCellType.allCases
            }
            return [.topImageList,.functionList,.advertise,.station,.documents]
        }
    }
    
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        titleForFooterRefreshWithNoMoreData = "--- 加载完成 ---"
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        
        //注册cell
        let cellClasses = [QDMPTopCycleTableViewCell.self,
                           QDNewMPItemsCycleTableViewCell.self,
                           QDMPNoticeTableViewCell.self,
                           QDMPAdCycleTableViewCell.self,
                           QDMPStationTableViewCell.self,
                           QDLineTextTableViewCell.self]
        
        let identifiers: [QDMainPageCellType] = [.topImageList,.functionList,.notices,.advertise,.station,.documents]
        
        //进行注册
        for (index,cellClass) in cellClasses.enumerated() {
            tableView.register(cellClass, forCellReuseIdentifier: identifiers[index].rawValue)
        }
    }
    
    override func headerRefreshBeginHandler() {
        itemCount = -1
        requestHomePageData()
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.addSubview(titleView)
        titleView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(BarDistance.NavigationBar.height)
        }
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(messageButton)
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.bottom.equalToSuperview().inset(10)
            make.height.equalTo(25)
        }
        
        messageButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview().inset(20)
            make.centerY.equalTo(titleLabel)
            make.width.height.equalTo(44)
        }
        
        //追加通知中心
        NotificationCenter.default.addObserver(self, selector: #selector(logStatusChangedAction), name: QDLogoutCompleteNotificationName, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(logStatusChangedAction), name: QDLoginCompleteNotificationName, object: nil)
        
        requestHomePageData()
        
//        QDImportantMessageView.show(title: "重要信息公告", topTitle: "尊敬的旅客您好：", detail: "因地铁APP系统出现网络异常，导致TVM扫码购票和地铁APP扫码乘车暂时无法使用，技术人员正在加紧修复，请您乘坐地铁时采取其他方式购票或进站乘车，给您出行造成的不便深表歉意，感谢您的谅解与支持。造成的不便深表歉意造成的不便深表歉意，造成的不便深表歉造成的不便深表歉造成的不便。表歉造成的不表")
    }
    
    /// 登陆登出
    @objc func logStatusChangedAction(){
        requestMessage()
        tableView.reloadData()//由于活动盒子进行手动刷新赋值
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        requestMessage()
        requestExigence()
    }
    
    /// 请求主页信息
    func requestHomePageData(){
        locationManager.updateLocationComplete({ [unowned self] (location) in

            self.requestMainList(longitude: CGFloat(location.coordinate.longitude/*120.45747098926107*/), latitude: CGFloat(/*36.098487534708099*/location.coordinate.latitude))

        }) { [unowned self] (error) in
            
            self.requestMainList(longitude: CGFloat(QDLocationManager.longitude().floatValue), latitude: CGFloat(QDLocationManager.latitude().floatValue))
        }
    }


    // MARK: NavigationBar
    override var nav_mutableBarShadowHidden: Bool { return true }
    override var nav_barHidden: Bool { return true }
    
    
    // MARK: Push
    /// 弹出信息列表控制器
    @objc func pushToMessageListViewController(){
//        checkLogin { [unowned self] in
//            self.router(platform: .messageIndex)
//        }
        let personCenter = PersonCenterViewController()
        self.navigationController?.pushViewController(personCenter, animated: true)
    }
    
    
    /// 弹出资讯列表控制器
    @objc func pushToNewsListViewController(){
        router(platform: .news)
    }
}



//MARK: UITableView 代理方法
extension QDMainPageTableViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return cellTypes.count
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellTypes[section] == .documents ? documents.count : 1
    }
    
    
    //TODO: cell方法待重构，将设置的值放在willDisplayer
    //TODO: cell方法待重构
    //TODO: cell方法待重构
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        /// 针对活动盒子的cell，设置活动盒子的key
        func updateHeziCollectionCell(cell: QDHDHZCycleCollectionViewCell,key: String){
            //重新设置代理
            cell.bannerView.delegate = self
            //设置默认图片
            cell.bannerView.setPlaceholder(#colorLiteral(red: 0.9215686275, green: 0.9215686275, blue: 0.9215686275, alpha: 1).ritl_image(), model: .scaleAspectFill)
            //设置key以及属性
            cell.bannerView.setPositionKey(key, properties: hzProperties())
        }
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellTypes[indexPath.section].rawValue, for: indexPath)
        
        
        /// 展示顶部轮播
        func topCellShow(cell: QDMPTopCycleTableViewCell){
            
            /// 针对普通的图片展示样式，只修改图片样式即可
            func updateCollectionCell(cell: SDCollectionViewCell){
                cell.imageView.clipsToBounds = true
                cell.imageView.layer.cornerRadius = 8
                cell.imageView.backgroundColor = .white
                cell.imageView.contentMode = .scaleAspectFill; return
            }
            
            if imgList.count == 0 { return }//不存在数据不刷新
            let imageUrls = imgList.map { $0.imgUrl }
            
            
            /// 配置什么样的样式cell
            cell.configCellIdentifierHandler = {[unowned self] (_,indexPath) in
                return self.imgList[indexPath.item].isBox ? QDSDCycleHZCellKey : QDSDCycleNormalCellKey
            }
            
            cell.cycleView.infiniteLoop = imageUrls.count > 1
            cell.cycleView.imageURLStringsGroup = imageUrls

            // 针对轮播的每个item进行单独的设置
            cell.customHandler = {[unowned self](_,cell,indexPath) in
                
                /// 针对普通的图片cell
                if let sdImageViewCell = cell as? SDCollectionViewCell {
                    updateCollectionCell(cell: sdImageViewCell)
                }
                
                /// 活动盒子
                if let heziIamgeViewCell = cell as? QDHDHZCycleCollectionViewCell {
                    updateHeziCollectionCell(cell: heziIamgeViewCell, key: self.imgList[indexPath.item].boxKey)
                }
            }
            
            //设置
            cell.selectHandler = {[unowned self] (_,index) in
                
                QDUMEventManager.event(event: .homeTop) //首页轮播埋点
                let imgObject = self.imgList[index]
                self.pushToShareWebViewController(url: imgObject.url, shareTitle: imgObject.title, autoTitle: false, title: "详情")
            }
        }
        
        
        /// 子模块展示
        func itemCellShow(cell: QDNewMPItemsCycleTableViewCell){
            
            //展示的图片url
            let images = functionList.map { $0.imgUrl }
            let realImages = images
            
            cell.shadowImageView.isHidden = hasNotice //如果存在紧急公告，阴影隐藏
            
            //展示的子标题
            let names = functionList.map { $0.title }
            let imageUrls = functionList.map { $0.imgUrl }
            
            //进行配置
            cell.configCellIdentifierHandler = { [unowned self] (_,indexPath) in
                return self.functionList[indexPath.item].isGif ? QDSDCycleAnimatedCellKey : QDSDCycleItemCellKey
            }
            
            //进行赋值
            cell.cycleView.imageURLStringsGroup = realImages
            
            //进行额外赋值
            cell.customHandler = {(_, cycleCell, indexPath) in
                if let collectionCell = cycleCell as? QDMPItemButtonCollectionViewCell {
                    collectionCell.titleLabel.text = names[indexPath.item]
                }
                
                if let collectionCell = cycleCell as? QDMPItemAnimableButtonCollectionViewCell {
                    collectionCell.titleLabel.text = names[indexPath.item]
                    collectionCell.animatedImageView.yy_imageURL = URL(string: imageUrls[indexPath.item])
                }
            }
            
            //进行点击响应
            cell.selectHandler = {[unowned self](_,index) in
                print("点击的是:\(names[index]), id:\(self.functionList[index].moduleId)")
                //获得typeId
                let function = self.functionList[index]
                let key = function.moduleId.functionPlatformKey
                switch key {
                case .web:
                    self.pushToShareWebViewController(url: function.linkUrl, shareTitle: function.title, title: function.title)
                default:
                     self.router(platform: self.functionList[index].moduleId.functionPlatformKey)
                }
            }
        }
        
        
        
        /// 紧急公告的展示
        func noticeCellShow(cell: QDMPNoticeTableViewCell){
            
            let notices = self.notices.map { $0.title }
            if notices.count == 0 { return }
            
            cell.noticeView.delegate = self
            
            // 限制的宽度
            let limitWidth = UIScreen.main.ritl_width - 53 - 8
            
            //文字的宽度,用来限制是否滚动
             func shouldScroll() -> Bool {
                
                // 文字的实际宽度
                let width = NSAttributedString(string: notices.first ?? "", attributes: [.font: Font.regular.font(size: 14)]).boundingRect(with: CGSize(width: 10000, height: 100), options: .usesLineFragmentOrigin, context: nil).size.width
                
                return width > limitWidth
            }
            
            print("我滚动属性是\(shouldScroll())")
            cell.noticeView.scrollable = shouldScroll()
            cell.title = notices.first// 设置跑马灯
        }
        
        
        /// 广告位
        func adCellShow(cell: QDMPAdCycleTableViewCell){
            
            let ads = advertisement.map { $0.imgUrl }
            if ads.count == 0 { return }//不存在数据不刷新
            
            /// 如果不重复
//            if let urls = cell.cycleView.imageURLStringsGroup, ads == urls as! [String] {
//                return
//            }
            
            // 适配活动盒子
            cell.configCellIdentifierHandler = {[unowned self] (_,indexPath) in
                return self.advertisement[indexPath.item].isBox ? QDSDCycleHZCellKey : QDSDCycleNormalCellKey
            }
            
            
            // 针对轮播的每个item进行单独的设置
            cell.customHandler = {[unowned self](_,cell,indexPath) in
                
                /// 针对普通的图片cell
                if let sdImageViewCell = cell as? SDCollectionViewCell {
                    sdImageViewCell.imageView.backgroundColor = 252.ritl_color;
                    sdImageViewCell.imageView.clipsToBounds = true;
                    sdImageViewCell.imageView.contentMode = .scaleAspectFill;
                }
                
                
                /// 活动盒子
                if let heziIamgeViewCell = cell as? QDHDHZCycleCollectionViewCell {
                    updateHeziCollectionCell(cell: heziIamgeViewCell, key: self.advertisement[indexPath.item].boxKey)
                }
            }
            
            
            cell.cycleView.infiniteLoop = false
            cell.cycleView.autoScroll = false
            cell.cycleView.imageURLStringsGroup = ads
            
            
            //设置
            cell.selectHandler = {[unowned self] (_,index) in
                
                let advertisement = self.advertisement[index]
                self.pushToShareWebViewController(url: advertisement.url, shareTitle: advertisement.title, autoTitle: false, title: "详情", qdmetro: true)
            }
        }
        
        
        
        /// 站点信息
        func stationCellShow(cell: QDMPStationTableViewCell){
            
            //获得站点信息
            cell.stationLabel.text = nearByStation.stationName
            cell.countLabel.text = "\(nearByStation.lineData.count)条路线经过此站"
            cell.distanceLabel.text = "距离约\(nearByStation.distance)"
            cell.distanceLabel.isHidden = nearByStation.distance.isEmpty
            
            if nearByStation.lineData.count == 0 {
                return;
            }
            
            //进行刷新
            cell.cycleView.imageURLStringsGroup = Array(repeating: "", count: nearByStation.lineData.count)
            
            //刷新地铁线路
            cell.customHandler = {[unowned self](_,cell,indexPath) in
                if let stationCell = cell as? QDMPStationCollectionViewCell { //设置属性
                    let station = self.nearByStation.lineData[indexPath.item]
                    
                    stationCell.lineLabel.text = "\(station.line)"
                    stationCell.lineLabel.backgroundColor = "\(station.lineId)".metroSelectColor
                    stationCell.endLabel.text = "Line \(station.line)"
                    
                    //单程线路站点
                    stationCell.backLineView.startLabel.text = station.thisStation
                    stationCell.backLineView.endLabel.text = station.startStation
                      
                    //时间
                    stationCell.backLineView.timeLabel.text = "首\(station.endFirst) 末\(station.endLast)"
                    stationCell.comeLineView.timeLabel.text = "首\(station.startFirst) 末\(station.startLast)"
                    
                    //返程线路站点
                    stationCell.comeLineView.startLabel.text = station.thisStation
                    stationCell.comeLineView.endLabel.text = station.endStation
                }
            }
            
            /// 点击
            cell.selectHandler = {[unowned self] (_,index) in
                
                let station = self.nearByStation
                if station.disable {  self.view.showTextHUD(text: "暂未开通"); return }
                
                //跳转车站详情
                self.router(platform: .stationDetail(id: station.stationId, name: station.stationName, fromMap: false, delegate: nil))
            }
        }
        
        
        /// 资讯
        func zixunCellShow(cell: QDLineTextTableViewCell){
            
            let document = documents[indexPath.row]
            
            //进行赋值
            cell.titleLabel.text = document.title
            cell.subtitleLabel.text = "\(document.author)  \(document.timeString)"
            cell.imageView.kf.setImage(with: URL(string: document.image))
            
            
            cell.backgroundColor = #colorLiteral(red: 0.9882352941, green: 0.9882352941, blue: 0.9882352941, alpha: 1)
            cell.contentView.backgroundColor = #colorLiteral(red: 0.9882352941, green: 0.9882352941, blue: 0.9882352941, alpha: 1)
            cell.imageView.backgroundColor = #colorLiteral(red: 0.9882352941, green: 0.9882352941, blue: 0.9882352941, alpha: 1)
            cell.subtitleLabel.backgroundColor = #colorLiteral(red: 0.9882352941, green: 0.9882352941, blue: 0.9882352941, alpha: 1)
            cell.titleLabel.backgroundColor = #colorLiteral(red: 0.9882352941, green: 0.9882352941, blue: 0.9882352941, alpha: 1)
        }
        

        //顶部轮播
        if let topCell = cell as? QDMPTopCycleTableViewCell { topCellShow(cell: topCell) }
        //子模块
        else if let itemCell = cell as? QDNewMPItemsCycleTableViewCell { itemCellShow(cell: itemCell) }
        //公告
        else if let noticeCell = cell as? QDMPNoticeTableViewCell  { noticeCellShow(cell: noticeCell) }
        //广告位
        else if let adCell = cell as? QDMPAdCycleTableViewCell { adCellShow(cell: adCell) }
        //站点样式
        else if let stationCell = cell as? QDMPStationTableViewCell { stationCellShow(cell: stationCell) }
        //资讯
        else if let textCell = cell as? QDLineTextTableViewCell { zixunCellShow(cell: textCell) }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        //返回高度
        switch cellTypes[indexPath.section] {
        case .topImageList: return QDMainPageCycleTopTableViewCellHeight()
        case .functionList: return ((hasNotice ? 160 : 169) - (isSmallerScreen() ? 3 : -1)/*85 + (hasNotice ? 0 : 9)*/ )
        case .notices: return 44
        case .advertise: return QDMainPageCycleAdTableViewCellHeight()
        case .station: return QDMPStationTableViewCellHeight(nearByStation.lineData.count, true, false)
        case .documents: return 101
        }
    }
    
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if cellTypes[section] == .documents { //资讯
            return sectionHeaderView
        }
        return UIView()
    }
    
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if cellTypes[section] == .documents { //资讯
            return 54
        }
        return .leastNormalMagnitude
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if cellTypes[indexPath.section] == .documents { //资讯
            let document = documents[indexPath.row]
            pushToShareWebViewController(url: document.webUrl, shareTitle: document.title, shareDesc: document.author,title: "资讯详情")
        }
    }
    
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        //如果是紧急公告
        if let noticeCell = cell as? QDMPNoticeTableViewCell/*,noticeCell.noticeView.marqueeView.shouldScroll*/ {
            noticeCell.run()
        }
    }
    
    
    override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        //如果是紧急公告
        if let noticeCell = cell as? QDMPNoticeTableViewCell {
            noticeCell.pause()
        }
    }
}



//MARK: QDNoticeViewDelegate 代理方法
extension QDMainPageTableViewController: QDNoticeViewDelegate {
    
    /// 点击的回调
    func noticeViewDidClick(view: QDNoticeView) {
        
        guard let webUrl = notices.first?.url, let title = notices.first?.title else { return }
        pushToShareWebViewController(url: webUrl, shareTitle: title, title: "详情")
    }
}



//MARK: 网络请求
extension QDMainPageTableViewController {
    
    /// 主页数据容器
    private struct QDHomeDataContainer: HandyJSON {
        
        /// 附近站点
        var nearByStation = QDNearMetroStationContainer()
        /// 资讯列表
        var documents = [QDDocumentsModel]()
        /// 子模块
        var functionList = [QDFunctionModel]()
        /// 顶部的轮播
        var imgList = [QDImageListModel]()
        /// 广告位
        var advertisement = [QDAdvertisementModel]()
        /// 公告
        var notices = [QDNoticesModel]()
    }
    
    /// 请求主页数据
    private func requestMainList(longitude: CGFloat,latitude: CGFloat){
        
        if !tableView.mj_header.isRefreshing {
            view.showWatingHUD()
        }
        
        QDNetworkingManager.request(url: homeUrl, paramteres: ["x": "\(latitude)","y": "\(longitude)","moduleId":"1"], success: { (msg, data) in
            
            self.view.dismissHUD()
            self.endHeaderRefreshing()
            
            //进行解析
            guard let container = QDHomeDataContainer.deserialize(from: data) else {
                self.view.showTextHUD(text: "数据结构错误!"); return
            }
            
            //进行赋值
            self.imgList = container.imgList
            self.functionList = container.functionList
            self.advertisement = container.advertisement
            self.nearByStation = container.nearByStation
            self.documents = container.documents
            
            //进行数据整合
            self.tableView.reloadData()
            self.refreshFooter.endRefreshingWithNoMoreData()
            
        }) { (msg, errorType) in
            
            self.view.dismissHUD()
            self.view.showTextHUD(text: msg)
            self.endHeaderRefreshing()
        }
    }
    
    
    /// 登陆完毕后进行请求
    private func requestMessage(){
        
        if !QDUserStatus.isLogin {
            messageButton.setImage("mp_notice".namedImage, for: .normal); return
        }
        
        QDNetworkingManager.request(url: QDStaticHostUrl  + "/message/checkNotRead",  success: { (msg, data) in
            
            guard let result = data["result"] as? String else { return }
            self.messageButton.setImage(result == "false" ? "mp_notice".namedImage : "mp_notice_read".namedImage, for: .normal)
        })
    }
    
    
    /// 请求紧急公告
    private func requestExigence() {
        
        // 后期需要优化此方法调用，需要整合
        QDNetworkingManager.request(url: exigenceUrl, success: { (msg, data) in
            
            guard let notice = QDNoticesModel.deserialize(from: data) else {
                self.notices.removeAll()
                self.tableView.reloadData(); return
            }
            
            if notice.hasNotices {
                self.notices = [notice]//进行存放
            }else {
                self.notices.removeAll()//消除
            }

            self.tableView.reloadData()
        })
    }
}



extension QDNetworkingManager {
    
    /// 请求紧急公告
    @objc static func requestUrgentNotices(complete:@escaping ((Bool,[String],[String])->(Void))){
        
        request(url: exigenceUrl, success: { (msg, data) in
            
            guard let notice = QDNoticesModel.deserialize(from: data) else {
                complete(false,[String](),[String]()); return
            }
            
            if notice.hasNotices {
                //进行赋值，刷新
                complete(true,[notice.title],[notice.url])
                
            }else {
                complete(false,[String](),[String]())
            }

        }) { (msg, type) in
            //不存在值
            complete(false,[String](),[String]())
        }
    }
}
